/**
 * 微信订阅消息工具函数
 */

import WechatTemplateMessage from './WechatTemplateMessage.js';

const templateMessage = new WechatTemplateMessage();

/**
 * 订阅提现相关消息
 * @returns {Promise<Object>} 订阅结果
 */
export function subscribeWithdrawMessages() {
	return new Promise((resolve) => {
		// #ifdef MP-WEIXIN
		const withdrawTemplates = templateMessage.getTemplateIds(['withdrawResult', 'withdrawFailed', 'withdrawSuccess']);
		
		wx.requestSubscribeMessage({
			tmplIds: withdrawTemplates,
			success: (res) => {
				// 检查订阅结果
				const results = Object.values(res);
				const hasAccepted = results.some(result => result === 'accept');
				const hasRejected = results.some(result => result === 'reject');
				const hasBanned = results.some(result => result === 'ban');
				
				resolve({
					success: true,
					hasAccepted,
					hasRejected,
					hasBanned,
					results: res
				});
			},
			fail: (err) => {
				console.error('提现消息订阅失败:', err);
				resolve({
					success: false,
					message: '订阅消息失败',
					error: err
				});
			}
		});
		// #endif
		
		// #ifndef MP-WEIXIN
		resolve({
			success: false,
			message: '当前环境不支持订阅消息'
		});
		// #endif
	});
}

/**
 * 订阅订单基础消息（新订单、接单、支付成功）
 * @returns {Promise<Object>} 订阅结果
 */
export function subscribeOrderBasicMessages() {
	return new Promise((resolve) => {
		// #ifdef MP-WEIXIN
		const orderTemplates = templateMessage.getTemplateIds(['newOrder', 'orderAccepted', 'paymentSuccess']);
		
		wx.requestSubscribeMessage({
			tmplIds: orderTemplates,
			success: (res) => {
				const results = Object.values(res);
				const hasAccepted = results.some(result => result === 'accept');
				const hasRejected = results.some(result => result === 'reject');
				const hasBanned = results.some(result => result === 'ban');
				
				resolve({
					success: true,
					hasAccepted,
					hasRejected,
					hasBanned,
					results: res
				});
			},
			fail: (err) => {
				console.error('订单基础消息订阅失败:', err);
				resolve({
					success: false,
					message: '订阅消息失败',
					error: err
				});
			}
		});
		// #endif
		
		// #ifndef MP-WEIXIN
		resolve({
			success: false,
			message: '当前环境不支持订阅消息'
		});
		// #endif
	});
}

/**
 * 订阅订单状态消息（接单、送达等）
 * @returns {Promise<Object>} 订阅结果
 */
export function subscribeOrderStatusMessages() {
	return new Promise((resolve) => {
		// #ifdef MP-WEIXIN
		const orderTemplates = templateMessage.getTemplateIds(['orderAccepted', 'product_order_delivered']);
		
		wx.requestSubscribeMessage({
			tmplIds: orderTemplates,
			success: (res) => {
				const results = Object.values(res);
				const hasAccepted = results.some(result => result === 'accept');
				const hasRejected = results.some(result => result === 'reject');
				const hasBanned = results.some(result => result === 'ban');
				
				resolve({
					success: true,
					hasAccepted,
					hasRejected,
					hasBanned,
					results: res
				});
			},
			fail: (err) => {
				console.error('订单状态消息订阅失败:', err);
				resolve({
					success: false,
					message: '订阅消息失败',
					error: err
				});
			}
		});
		// #endif
		
		// #ifndef MP-WEIXIN
		resolve({
			success: false,
			message: '当前环境不支持订阅消息'
		});
		// #endif
	});
}

/**
 * 订阅订单相关消息（兼容旧版本）
 * @returns {Promise<Object>} 订阅结果
 */
export function subscribeOrderMessages() {
	return new Promise(async (resolve) => {
		// #ifdef MP-WEIXIN
		try {
			// 将订单模板分批处理，每批最多3个
			const orderTemplateKeys = ['newOrder', 'orderCancelled', 'orderCompleted', 'orderAccepted', 'paymentSuccess', 'product_order_delivered'];
			const batches = [];
			
			// 分批处理，每批最多3个模板
			for (let i = 0; i < orderTemplateKeys.length; i += 3) {
				batches.push(orderTemplateKeys.slice(i, i + 3));
			}
			
			let allResults = {};
			let hasAccepted = false;
			let hasRejected = false;
			let hasBanned = false;
			
			// 逐批订阅
			for (let i = 0; i < batches.length; i++) {
				const batchTemplates = templateMessage.getTemplateIds(batches[i]);
				
				const batchResult = await new Promise((batchResolve) => {
					wx.requestSubscribeMessage({
						tmplIds: batchTemplates,
						success: (res) => {
							batchResolve({ success: true, results: res });
						},
						fail: (err) => {
							console.error(`订单消息订阅批次 ${i + 1} 失败:`, err);
							batchResolve({ success: false, error: err });
						}
					});
				});
				
				if (batchResult.success) {
					// 合并结果
					Object.assign(allResults, batchResult.results);
					
					// 检查订阅状态
					const results = Object.values(batchResult.results);
					hasAccepted = hasAccepted || results.some(result => result === 'accept');
					hasRejected = hasRejected || results.some(result => result === 'reject');
					hasBanned = hasBanned || results.some(result => result === 'ban');
				} else {
					// 如果某一批失败，返回失败结果
					resolve({
						success: false,
						message: '订阅消息失败',
						error: batchResult.error
					});
					return;
				}
			}
			
			resolve({
				success: true,
				hasAccepted,
				hasRejected,
				hasBanned,
				results: allResults
			});
		} catch (error) {
			console.error('订单消息订阅失败:', error);
			resolve({
				success: false,
				message: '订阅消息失败',
				error: error
			});
		}
		// #endif
		
		// #ifndef MP-WEIXIN
		resolve({
			success: false,
			message: '当前环境不支持订阅消息'
		});
		// #endif
	});
}

/**
 * 订阅社区消息（违规警告、举报通知、审核结果）
 * @returns {Promise<Object>} 订阅结果
 */
export function subscribeCommunityMessages() {
	return new Promise((resolve) => {
		// #ifdef MP-WEIXIN
		const communityTemplates = templateMessage.getTemplateIds(['violationWarning', 'reportedNotification', 'auditResult']);
		
		wx.requestSubscribeMessage({
			tmplIds: communityTemplates,
			success: (res) => {
				const results = Object.values(res);
				const hasAccepted = results.some(result => result === 'accept');
				const hasRejected = results.some(result => result === 'reject');
				const hasBanned = results.some(result => result === 'ban');
				
				resolve({
					success: true,
					hasAccepted,
					hasRejected,
					hasBanned,
					results: res
				});
			},
			fail: (err) => {
				console.error('社区消息订阅失败:', err);
				resolve({
					success: false,
					message: '订阅消息失败',
					error: err
				});
			}
		});
		// #endif
		
		// #ifndef MP-WEIXIN
		resolve({
			success: false,
			message: '当前环境不支持订阅消息'
		});
		// #endif
	});
}

/**
 * 订阅系统消息（站内信）
 * @returns {Promise<Object>} 订阅结果
 */
export function subscribeSystemMessages() {
	return new Promise((resolve) => {
		// #ifdef MP-WEIXIN
		const systemTemplates = templateMessage.getTemplateIds(['internalMessage']);
		
		wx.requestSubscribeMessage({
			tmplIds: systemTemplates,
			success: (res) => {
				const results = Object.values(res);
				const hasAccepted = results.some(result => result === 'accept');
				const hasRejected = results.some(result => result === 'reject');
				const hasBanned = results.some(result => result === 'ban');
				
				resolve({
					success: true,
					hasAccepted,
					hasRejected,
					hasBanned,
					results: res
				});
			},
			fail: (err) => {
				console.error('系统消息订阅失败:', err);
				resolve({
					success: false,
					message: '订阅消息失败',
					error: err
				});
			}
		});
		// #endif
		
		// #ifndef MP-WEIXIN
		resolve({
			success: false,
			message: '当前环境不支持订阅消息'
		});
		// #endif
	});
}

/**
 * 一键订阅所有消息
 * @returns {Promise<Object>} 订阅结果
 */
export function subscribeAllMessages() {
	return new Promise(async (resolve) => {
		// #ifdef MP-WEIXIN
		try {
			// 获取所有模板ID
			const allTemplateIds = templateMessage.getAllTemplateIds();
			const templateIds = Object.values(allTemplateIds);
			
			// 分批处理，每批最多3个
			const firstBatch = templateIds.slice(0, 3);
			
			const res = await new Promise((batchResolve) => {
				wx.requestSubscribeMessage({
					tmplIds: firstBatch,
					success: (res) => {
						batchResolve({ success: true, results: res });
					},
					fail: (err) => {
						console.error('一键订阅失败:', err);
						batchResolve({ success: false, error: err });
					}
				});
			});
			
			if (res.success) {
				const results = Object.values(res.results);
				const hasAccepted = results.some(result => result === 'accept');
				const hasRejected = results.some(result => result === 'reject');
				const hasBanned = results.some(result => result === 'ban');
				
				resolve({
					success: true,
					hasAccepted,
					hasRejected,
					hasBanned,
					results: res.results
				});
			} else {
				resolve({
					success: false,
					message: '订阅消息失败',
					error: res.error
				});
			}
		} catch (error) {
			console.error('一键订阅失败:', error);
			resolve({
				success: false,
				message: '订阅消息失败',
				error: error
			});
		}
		// #endif
		
		// #ifndef MP-WEIXIN
		resolve({
			success: false,
			message: '当前环境不支持订阅消息'
		});
		// #endif
	});
}

/**
 * 打开订阅消息设置页面
 * @returns {Promise<Object>} 设置结果
 */
export function openSubscriptionSettings() {
	return new Promise((resolve) => {
		// #ifdef MP-WEIXIN
		wx.openSetting({
			success: (res) => {
				resolve({
					success: true,
					results: res
				});
			},
			fail: (err) => {
				console.error('打开设置失败:', err);
				resolve({
					success: false,
					message: '打开设置失败',
					error: err
				});
			}
		});
		// #endif
		
		// #ifndef MP-WEIXIN
		resolve({
			success: false,
			message: '当前环境不支持打开设置'
		});
		// #endif
	});
}

/**
 * 检查订阅消息权限
 * @returns {Promise<Object>} 权限检查结果
 */
export function checkSubscriptionPermission() {
	return new Promise((resolve) => {
		// #ifdef MP-WEIXIN
		wx.getSetting({
			withSubscriptions: true,
			success: (res) => {
				const hasPermission = res.subscriptionsSetting && res.subscriptionsSetting.mainSwitch;
				resolve({
					success: true,
					hasPermission,
					settings: res.subscriptionsSetting || {}
				});
			},
			fail: (err) => {
				console.error('获取设置失败:', err);
				resolve({
					success: false,
					message: '获取设置失败',
					error: err
				});
			}
		});
		// #endif
		
		// #ifndef MP-WEIXIN
		resolve({
			success: false,
			message: '当前环境不支持此功能'
		});
		// #endif
	});
}

/**
 * 检查特定模板的订阅状态
 * @param {Array} tmplIds 模板ID数组
 * @returns {Promise<Object>} 订阅状态检查结果
 */
export function checkTemplateSubscriptionStatus(tmplIds) {
	return new Promise((resolve) => {
		// #ifdef MP-WEIXIN
		wx.getSetting({
			withSubscriptions: true,
			success: (res) => {
				const subscriptionsSetting = res.subscriptionsSetting || {};
				const itemSettings = subscriptionsSetting.itemSettings || {};
				
				const status = {};
				tmplIds.forEach(tmplId => {
					status[tmplId] = itemSettings[tmplId] || 'not_set';
				});
				
				resolve({
					success: true,
					mainSwitch: subscriptionsSetting.mainSwitch || false,
					itemSettings: status
				});
			},
			fail: (err) => {
				console.error('获取订阅状态失败:', err);
				resolve({
					success: false,
					message: '获取订阅状态失败',
					error: err
				});
			}
		});
		// #endif
		
		// #ifndef MP-WEIXIN
		resolve({
			success: false,
			message: '当前环境不支持此功能'
		});
		// #endif
	});
}

/**
 * 发送提现相关模板消息（后端调用）
 * @param {string} type 消息类型
 * @param {Object} data 消息数据
 * @returns {Promise<Object>} 发送结果
 */
export function sendWithdrawTemplateMessage(type, data) {
	// 这里应该调用后端API发送模板消息
	// 前端主要负责订阅和权限管理
	return new Promise((resolve) => {
		resolve({
			success: true,
			message: '模板消息发送成功'
		});
	});
} 

// 保持向后兼容
export const subscribeWithdrawProgress = subscribeWithdrawMessages; 